<template>
  <div class="shift-detail">
    <n-card v-if="loading" :bordered="false" class="proCard">
      <n-spin :show="loading" class="loading" />
    </n-card>

    <DFPageDetail v-else :page-options="pageOptions" />
  </div>
</template>

<script lang="ts" setup name="ShiftDetail">
  import type { SelectOption } from 'naive-ui';
  import lang from '../lang';
  import { useMixins } from '@/hooks/useMixins';
  import { addShift, shiftInfo, updateShift } from '@/api/base/shift';
  import { listWorkType } from '@/api/base/workType';
  import { listUser } from '@/api/system/user';
  import { generateRandomValue } from '@/utils/index';

  const { t, loadLangFn, routerType, message } = useMixins();

  const loading = ref(false);

  const userList = ref([]);

  const workTypeList = ref([]);
  const workTypeSelectedList = ref([]);

  loadLangFn(lang);

  // const handleEditDataFn = (res: any = {}) => {
  //   console.log(res);
  //     return res;
  //   };

  async function initFn() {
    try {
      if (routerType !== 'check') {
        loading.value = true;

        const res = await Promise.all([listUser(), listWorkType()]);

        const [list1, list2] = res;

        userList.value = list1.data.map((item) => ({
          label: `${item.nickName}(${item.userName})`,
          value: item.id,
        }));

        // console.log(list1)

        workTypeList.value = list2.data.map((item) => ({
          label: item.workTypeName,
          value: item.workTypeCode,
        }));

        loading.value = false;

        // setTimeout(() => {
        //   loading.value = false;
        // }, 000);
      }
    } catch (_e) {
      // console.log(_e);
    }
  }

  const checkSubmitFn = (editTableData = []) => {
    let isSubmit = true;
    if (editTableData && editTableData.length) {
      isSubmit =
        editTableData.filter((item) => {
          return editTableData.some(
            (otherItem) => otherItem.userId === item.userId && otherItem !== item
          );
        }).length === 0;
    }
    if (!isSubmit) {
      message.error(`${t('shift.tipMsg.submitErr')}`);
    }
    return isSubmit;
  };

  const beforeSubmitFn = (data: any = {}, _refData: any = {}) => {
    const { userList = [] } = data;

    console.log('userList', userList);

    return checkSubmitFn(userList);
  };

  const pageOptions = {
    list: [
      {
        type: 'form',
        formSchemas: [
          {
            label: 'shiftName',
            required: true,
            editDisabled: true,
          },
          {
            label: 'shiftCode',
            required: true,
            editDisabled: true,
          },
          {
            label: 'remark',
            type: 'textarea',
            common: true,
            giProps: { span: 3 },
            componentProps: {
              'show-count': true,
            },
          },
        ],
      },
      {
        title: t('shift.table.tableName'),
        type: 'table',
        hasSelection: true,
        ref: 'userList',
        columns: [
          {
            label: 'nickName',
            prop: 'userId',
            common: true,
            required: true,
            itemData: {
              maxlength: 20,
              component: 'NSelect',
              options: userList,
            },
          },
          {
            label: 'workTypeName',
            prop: 'workTypeCode',
            required: true,
            itemData: {
              maxlength: 20,
              component: 'NSelect',
              options: workTypeList,
              componentProps: {
                filterable: true,
                tag: true,
                'on-create': (label: string) => {
                  const workTypeCode = generateRandomValue(16);
                  const workTypeItem = workTypeSelectedList.value.find(
                    (item) => item.label === label
                  );
                  return { label, value: workTypeItem ? workTypeItem.value : workTypeCode };
                },
                'onUpdate:value': (_val: string, option: SelectOption) => {
                  if (
                    option &&
                    !workTypeSelectedList.value.some((item) => item.label === option.label)
                  )
                    workTypeSelectedList.value.push(option);
                },
              },
            },
          },
        ],
      },
    ],
    formLabelWidthEn: 100,
    descriptionsListLabelWidthEn: 150,
    routeName: 'shift',
    addDataFn: addShift,
    updateDataFn: updateShift,
    getDataFn: shiftInfo,
    setSubmitDataFn: (data, type) => {
      data.userList = data.userList.map((item) => {
        const { id, workTypeCode } = item;
        return {
          ...item,
          id: type === 'add' ? undefined : id,
          workTypeName: (workTypeSelectedList.value.find((i) => i.value === workTypeCode) || {})
            .label,
        };
      });
      return data;
    },
    // handleEditDataFn,
    beforeSubmitFn,
  };

  initFn();
</script>

<style lang="less" scoped>
  .shift-detail {
    position: relative;

    .loading {
      width: 100%;
      position: absolute;
      top: 50%;
      transform: translateY(-50%);
    }
  }
</style>
